package com.kgc.crowd.ossdemo.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.kgc.crowd.ossdemo.config.OSSProperties;

import java.io.InputStream;
import java.util.UUID;

public class AliyunOSSUtil {

    public static String upload(InputStream inputStream,String oldfileName){

        String endpoint = OSSProperties.ENDPOINT;
        String accessKeyId = OSSProperties.ACCESS_KEY_ID;
        String accessKeySecret = OSSProperties.ACCESS_KEY_SECRET;
        String bucketName= OSSProperties.BUCKET_NAME;
        String folderName= OSSProperties.FOLDER_NAME;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //生成新的文件名
        String newFileName= UUID.randomUUID().toString().replaceAll("-","")+oldfileName;
        String fileURL=folderName+"/"+newFileName;
        // 上传文件流。
        try {
            ossClient.putObject(bucketName, fileURL, inputStream);
        }catch (Exception ex){
            ex.printStackTrace();
        }finally {
            // 关闭OSSClient。
            ossClient.shutdown();
        }

        return fileURL;
    }
}
